import React from 'react';
import { Upload,Icon,message } from 'antd';
import Utils from '@/utils/utils';
import { fileDirectory } from "@/config/systemConfig";
import { UploadBaseUrl } from '@/utils/globalConst';
import './index.less';

export default class UploadImage extends React.Component {
    state = {
        data: [],
    }
    index = 0;
    componentWillMount() {
       
    }
    //上传文件之前的操作  图片限制
    handleBeforeUpload = (file) => {
        const isLt2M = file.size / 1024 / 1024 < 10;
        if (!isLt2M) {
            message.error('图片不能超过10MB!');
        }
        return isLt2M;
    }
    //选择图片文件
    handleChange = (info) => {
        if (info.file.status === 'uploading') {
            this.setState({
                uploadLoading: true
            })
        } else if (info.file.status === 'done') {          
            if (info.file.response.code != 0) {
                message.error(`上传失败，${info.file.response.msg}`);
                this.setState({
                    uploadLoading: false,
                })
            } else {   
                message.success(`${info.file.name} 上传成功`);
                Utils.getBase64(info.file.originFileObj, imageUrl => {
                    this.setState({
                        uploadLoading: false,
                        imageUrl
                    })
                    this.props.getImageUrl(imageUrl);
                });
            }
        } else if (info.file.status === 'error') {
            this.setState({
                uploadLoading: false
            })
            message.error(`${info.file.name} 上传失败，请重新上传！`);
        }
    }    
   
    render() {
        //文件上传
        const props = {
            name: 'file',
            listType: "picture-card",
            accept: "image/*",
            showUploadList: false,
            disabled: this.state.uploadLoading,
            action: UploadBaseUrl + '/att/attachment/singleUploadToDir?categoryDir=' + fileDirectory.common,
            headers: {
                authorization: 'authorization-text',
                'X-Api-Key': localStorage.getItem("X-Api-Key"),
                "X-User-Id": localStorage.getItem("X-User-Id"),
                "X-Client-Id": localStorage.getItem("browserFingerprint"),
            },
            beforeUpload: this.handleBeforeUpload,
            onChange: this.handleChange,
        };
        const uploadButton = (
            <div>
                <Icon type={this.state.uploadLoading ? 'loading' : 'plus'} />
                <div className="ant-upload-text">上传图片</div>
            </div>
        );
        const imageUrl = this.state.imageUrl;
        return (
            <div>
                <Upload
                    {...props}
                >
                    {imageUrl ? <img src={imageUrl} alt="icon" className="preview-img" /> : uploadButton}
                </Upload>
            </div>
        )
    }
}